package com.xiewz;

import com.xiewz.executor.Executor;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Trasfer {

    private static String mdFilePath = null;
    /**
     * 记录替换的记录
     */
    private static Map<String, Integer> recordMap = new HashMap<String, Integer>();
    /**
     * 文件内容
     */
    private static StringBuffer content = null;

    public static StringBuffer getContent() {
        return content;
    }

    public static Map<String, Integer> getRecordMap() {
        return recordMap;
    }

    /**
     * JDK11 读取与加载文件
     *
     * @param fileName 读取源文件名
     * @return
     */
    public static StringBuffer loadByFile(String fileName) {
        mdFilePath = fileName;
        StringBuffer sbf = new StringBuffer();
        try {
            // 读取字节流
            byte[] bytes = Files.readAllBytes(Paths.get(fileName));
            sbf = new StringBuffer(new String(bytes, "utf-8"));
            return content = sbf;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return content = sbf;
    }

    /**
     * 替换指定字符串
     *
     * @param org    被替换的字符串
     * @param result 替换成的字符串
     * @return
     */
    public static StringBuffer replaceStr(String org, String result) {
        if (content == null) {
            return content;
        }
        int index = content.indexOf(org);
        while (index >= 0) {
            content.replace(index, index + org.length(), result);

            index = content.indexOf(org);

            Integer count = recordMap.get(org);
            // 替换次数
            recordMap.put(org, count == null ? 1 : ++count);
        }
        return content;
    }

    /**
     * 替换图片路径
     */
    static void replaceImgPath(Executor executor) {

        System.out.println("----------替换开始-------------------");
        Pattern pattern = Pattern.compile("\\!([\\[].*?[](].*?)\\)");
        Matcher matcher = pattern.matcher(content);
        // 替换后的完整内容
        StringBuffer temp;
        String value;
        for(temp = new StringBuffer();matcher.find();matcher.appendReplacement(temp,value)) {
            String key = matcher.group(1);
            System.out.println("匹配内容：" + key);
            // 获取文件全路径
            int subInd = key.indexOf("](");
            String filepath = subInd >= 0 ? key.substring(subInd + 2) : null;
            Object markdownStr = executor.doExecutor(filepath);
            value = markdownStr == null || "".equals(markdownStr) ? String.format("!%s)", key) : markdownStr.toString();
            System.out.println("替换后的内容：" + value);
        }
        matcher.appendTail(temp);
        // 重新赋值
        content = temp;
        System.out.println("--------替换结束----------");
//        System.out.println(temp);

    }


    /**
     * 以默认UTF-8编码，存储内容到指定文件
     *
     * @param destFileName 目标文件名
     */
    public static void saveToFile(String destFileName) {
        recordMap.clear();
        try {

            // Java 11 , default StandardCharsets.UTF_8
            // Files.writeString(Paths.get(destFileName), content);
            // java 1.8
            Files.write(Paths.get(destFileName), content.toString().getBytes(StandardCharsets.UTF_8));

            // encoding
            // Files.writeString(Paths.get(path), content, StandardCharsets.US_ASCII);

            // extra options
            // Files.writeString(Paths.get(path), content,
            //		StandardOpenOption.CREATE, StandardOpenOption.APPEND);
            System.out.println("save success");

        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
